# coding: utf-8
import json
from pathlib import Path
from typing import Union

from pydantic import BaseModel


def read(self: BaseModel):
    return json.dumps(json.loads(self.json()), indent=2, ensure_ascii=False)


def save(self: BaseModel, file_path: Union[Path, str]):
    if isinstance(file_path, str):
        file_path = Path(file_path)
    with file_path.open('w', encoding='utf-8') as fp:
        fp.write(self.read())


def load(file_path: Union[Path, str]) -> Union[dict, None]:
    if isinstance(file_path, str):
        file_path = Path(file_path)
    if file_path.exists():
        with file_path.open('r', encoding='utf-8') as fp:
            data = json.load(fp)
            return data
    return None
